package edu.friday.controller;

import edu.friday.common.base.BaseController;
import edu.friday.common.constant.UserConstants;
import edu.friday.common.result.RestResult;
import edu.friday.common.result.TableDataInfo;
import edu.friday.model.vo.SysRoleVO;
import edu.friday.service.SysMenuService;
import edu.friday.service.SysRoleService;
import edu.friday.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/system/role")
public class SysRoleController extends BaseController {
    @Autowired
    SysRoleService roleService;
    @Autowired
    SysMenuService menuService;

    @GetMapping("/list")
    public TableDataInfo list(SysRoleVO roleVO, Pageable page){
        int pageNum=page.getPageNumber()-1;
        pageNum=pageNum<=0 ? 0 : pageNum;
        page= PageRequest.of(pageNum,page.getPageSize());
        return roleService.selectRoleList(roleVO,page);
    }

    @PostMapping("/addRole")
    public RestResult addRole(@RequestBody SysRoleVO sysRoleVO){
        if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleNameUnique(sysRoleVO.getRoleName()))) {
            return RestResult.error("新增角色"+sysRoleVO.getRoleName()+"失败，角色已存在");
        }sysRoleVO.setCreateBy("system");
        return roleService.insertRole(sysRoleVO);
    }

    @GetMapping(value = {"/","/{roleId}"})
    public RestResult getInfo(@PathVariable(value = "roleId",required = false) Long roleId){
        RestResult ajax=RestResult.success();
        ajax.put("menuIds",menuService.selectMenuRoleId(roleId));
        if (StringUtils.isNotNull(roleId)) {
            ajax.put(RestResult.DATA_TAG,roleService.selectRoleMenuById(roleId));
        }
        return ajax;
    }


    @PutMapping("/changeStatus")
    public int changeStatus(Long roleId, String status){
        return roleService.updateStatus(roleId,status);
    }
}
